package com.bcinfo.iccard.codec;

import java.util.Arrays;

import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.bcinfo.iccard.msg.ISOMessageFactory;
import com.bcinfo.iccard.msg.Message;
/**
 * ISO8583报文编码器
 * @author wangguangchun
 *
 */
public class ISO8583Encoder extends ProtocolEncoderAdapter {

	private Logger _logger=Logger.getLogger(getClass());
	@Override
	public void encode(IoSession ioSession, Object msg, ProtocolEncoderOutput out)
			throws Exception {
		if(_logger.isDebugEnabled()){
			_logger.debug("encode:client is "+ioSession.getRemoteAddress());
		}
		Message message=(Message)msg;
		ISOMessageFactory.print(message.getMsg());
		byte[] msgBuf=message.getMsg().writeData();
		byte[] tpduBuf=message.getTpdu();
		//消息体长度
		int msgLen=msgBuf.length;
		int totalLength=msgLen+tpduBuf.length;
		//本接口协议长度使用2个字节16进制表示,故取整型对应byte数组的低2位
		byte[] lenBuf=Arrays.copyOfRange(CodeUtils.intToByte(totalLength), 2, 4);
		IoBuffer buf = IoBuffer.allocate(128).setAutoExpand(true);
		//写长度
		buf.put(lenBuf);
		//写TPDU头
		buf.put(message.getTpdu());
		//写消息体
		buf.put(msgBuf);
		buf.flip();
		if(_logger.isDebugEnabled()){
			_logger.debug("write msg to client:" +buf.toString());
		}
		out.write(buf);
	}

}
